package manifests

import (
	sredisv1 "git.blindage.org/21h/single-redis-operator/api/v1"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/intstr"
)

func GenerateService(cr *sredisv1.SingleRedis, serviceName string, ports map[string]int32, labels map[string]string) corev1.Service {

	labelsComplete := MergeLabels(BaseLabels(cr), labels)

	service := corev1.Service{
		ObjectMeta: metav1.ObjectMeta{
			Name:      serviceName,
			Namespace: cr.Namespace,
			Labels:    BaseLabels(cr),
		},
	}

	service.Spec.Type = corev1.ServiceTypeClusterIP

	service.Spec.Ports = []corev1.ServicePort{}
	for portName, portNum := range ports {
		port := corev1.ServicePort{
			Name:       portName,
			Port:       portNum,
			Protocol:   corev1.ProtocolTCP,
			TargetPort: intstr.FromString(portName),
		}
		service.Spec.Ports = append(service.Spec.Ports, port)
	}

	service.Spec.Selector = labelsComplete

	return service
}
